import { ActionReducerMapBuilder, createAsyncThunk, createSlice, PayloadAction, Slice, type AsyncThunk } from "@reduxjs/toolkit"
import { getVersion, GetVersionParams } from "./versionAPI"
import { DataType } from "@/pages/Version/Table"

interface InitialState {
  params: GetVersionParams,
  table: {
    status: 'init' | 'loading' | 'success' | 'error',
    data?: Res,
    params?: GetVersionParams
  },
  create: {
    type: 'create' | 'update',
    open: boolean,
    record?: DataType
  }
}

const initialState: InitialState = {
  params: {
    channel: '',
    page: 1,
    page_size: 10
  },
  table: {
    status: "init"
  },
  create: {
    type: 'create',
    open: false
  }
}

type Res = {
  data: {
    count: number,
    data: DataType[],
    page: number
  }
}
type AsyncRes = {
  res: Res,
  params: GetVersionParams
}
export const getVersionAsync: AsyncThunk<AsyncRes, GetVersionParams, {}> = createAsyncThunk<AsyncRes, GetVersionParams, {}>('version.getVersionAsync', async params => {
  const res: Res = await getVersion(params)
  return {
    res, params
  }
})
const tableStatus = (builder: ActionReducerMapBuilder<InitialState>) => {
  builder.addCase(getVersionAsync.pending, state => {
    state.table.status = 'loading'
  }).addCase(getVersionAsync.fulfilled, (state, action) => {
    state.table.status = 'success'
    state.table.data = action.payload.res
    state.table.params = action.payload.params
  }).addCase(getVersionAsync.rejected, state => {
    state.table.status = 'error'
  })
}

type Reducers = {
  changeParams: (state:InitialState, action: PayloadAction<Partial<InitialState['params']>>) => void,
  changeCreate: (state:InitialState, action: PayloadAction<Partial<InitialState['create']>>) => void
}
type Selectors = {}
const versionSlice:Slice<InitialState, Reducers, 'version', 'version', Selectors> = createSlice<InitialState, Reducers, 'version', Selectors, 'version'>({
  name: 'version',
  initialState,
  reducers:{
    changeParams(state, action){
      state.params = {
        ...state.params,
        ...action.payload
      }
    },
    changeCreate(state, action){
      state.create = {
        ...state.create,
        ...action.payload
      }
    }
  },
  extraReducers(builder){
    tableStatus(builder)
  }
})

export const { changeParams, changeCreate } = versionSlice.actions

export default versionSlice.reducer